package cn.itsource.user.controller;

import cn.itsource.basic.constant.PetHomeConstant;
import cn.itsource.basic.util.AxajResult;
import cn.itsource.user.domain.dto.UserDto;
import cn.itsource.user.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    private IWechatService wechatService;
    /**
     * 发送get请求，获取授权码
     * @return
     */
    @GetMapping("/toRequestCode")
    public String toRequestCode(){
        return "redirect:"+ PetHomeConstant.CODEURL.replace("APPID", PetHomeConstant.APPID)
                .replace("REDIRECT_URI", PetHomeConstant.REDIRECT_URI);
    }
    @RequestMapping("/callback")
    public String callback(String code) {
        //跳转到门户网站callback.html页面，在此页面发送ajax请求获取token
        return "redirect:http://localhost:8082/callback.html?code=" + code;
    }

    /**
     * 根据code获取token
     * @param parm
     * @return
     */
    @PostMapping("/handleCallBack")
    @ResponseBody
    public AxajResult handleCallBack(@RequestBody Map<String,String> parm){
        try {
            String code = parm.get("code");
            //通过code获取token值
            Map<String,Object> map=wechatService.handleCallBack(code);
            return new AxajResult().setObjResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AxajResult(false,e.getMessage());
        }
    }
    @PostMapping("/binder")
    @ResponseBody
    public AxajResult binder(@RequestBody UserDto userDto){
        try {
            Map<String,Object> map=wechatService.binder(userDto);
            return new AxajResult().setObjResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AxajResult(false,e.getMessage());
        }
    }
}
